package com.example.demotest.controller;

import com.example.demotest.pojo.Order;
import com.example.demotest.pojo.dto.DeleteOrderDto;
import com.example.demotest.pojo.dto.OrderCreateDto;
import com.example.demotest.pojo.dto.OrderDetailDto;
import com.example.demotest.pojo.dto.OrderPayDto;
import com.example.demotest.pojo.dto.OrderStatusDto;
import com.example.demotest.service.IOrderService;
import com.example.demotest.util.JWT;
import com.example.demotest.util.ResponseMessage;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@RestController
@RequestMapping("/order")
public class OrderController {

    @Autowired
    private IOrderService orderService;

    @Autowired
    private JWT jwt;

    // ========================== 创建订单 ==========================
    @PostMapping("/create")
    public ResponseMessage<?> createOrder(
            @RequestBody @Valid OrderCreateDto orderDto,
            HttpServletRequest request) {
        String token = jwt.extractToken(request);
        if (token == null || !jwt.validateToken(token)) {
            return ResponseMessage.error(401, "请先登录");
        }

        try {
            Integer buyerId = jwt.getUserIdFromToken(token);
            Order newOrder = orderService.createOrder(buyerId, orderDto);
            return ResponseMessage.success(newOrder);
        } catch (RuntimeException e) {
            return ResponseMessage.error(400, e.getMessage());
        } catch (Exception e) {
            return ResponseMessage.error(500, "服务器内部错误");
        }
    }

    // ========================== 获取订单详情 ==========================
    @GetMapping("/get")
    public ResponseMessage<?> getOrderDetail(
            @RequestParam("id") Integer orderId,
            HttpServletRequest request) {
        String token = jwt.extractToken(request);
        if (token == null || !jwt.validateToken(token)) {
            return ResponseMessage.error(401, "请先登录");
        }

        try {
            Integer userId = jwt.getUserIdFromToken(token);
            OrderDetailDto result = orderService.getOrderDetail(orderId, userId);
            return ResponseMessage.success(result);
        } catch (RuntimeException e) {
            return ResponseMessage.error(404, e.getMessage());
        } catch (Exception e) {
            return ResponseMessage.error(500, "服务器内部错误");
        }
    }

    // ========================== 支付订单 ==========================
    @PostMapping("/pay/{orderId}")
    public ResponseMessage<?> payOrder(
            @PathVariable("orderId") Integer orderId,
            @RequestBody @Valid OrderPayDto payDto,
            HttpServletRequest request) {
        String token = jwt.extractToken(request);
        if (token == null || !jwt.validateToken(token)) {
            return ResponseMessage.error(401, "请先登录");
        }

        try {
            Integer userId = jwt.getUserIdFromToken(token);
            boolean result = orderService.payOrder(orderId, userId, payDto);
            return ResponseMessage.success(result ? "支付成功" : "支付失败");
        } catch (RuntimeException e) {
            e.printStackTrace();  // ✨加上这个！
            return ResponseMessage.error(400, e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseMessage.error(500, "服务器内部错误");
        }
    }

    // ========================== 修改订单状态 ==========================
    @PostMapping("/update")
    public ResponseMessage<?> updateOrderStatus(
            @RequestBody @Valid OrderStatusDto statusDto,
            HttpServletRequest request) {
        String token = jwt.extractToken(request);
        if (token == null || !jwt.validateToken(token)) {
            return ResponseMessage.error(401, "请先登录");
        }

        try {
            Integer userId = jwt.getUserIdFromToken(token);
            Integer orderId = statusDto.getId();  // 获取正确的订单ID
            
            // 验证权限
            /*
            if (!orderService.isSellerOrAdmin(statusDto.getOrderStatus(), userId)) {
                return ResponseMessage.error(403, "无权限执行此操作");
            }
            */
            
            // 调用服务层更新状态
            boolean result = orderService.updateOrderStatus(orderId, userId, statusDto);
            
            if (result) {
                // 返回更新后的订单信息
                OrderDetailDto updatedOrder = orderService.getOrderDetail(orderId, userId);
                return ResponseMessage.success(updatedOrder);
            } else {
                return ResponseMessage.error(400, "状态更新失败");
            }
        } catch (RuntimeException e) {
            e.printStackTrace(); // 添加日志输出
            return ResponseMessage.error(400, e.getMessage());
        } catch (Exception e) {
            e.printStackTrace(); // 添加日志输出
            return ResponseMessage.error(500, "服务器内部错误");
        }
    }

    // ========================== 删除订单 ==========================
    @PostMapping("/delete")
    public ResponseMessage<?> deleteOrder(
            @RequestBody @Valid DeleteOrderDto deleteDto,
            HttpServletRequest request) {
        String token = jwt.extractToken(request);
        if (token == null || !jwt.validateToken(token)) {
            return ResponseMessage.error(401, "请先登录");
        }

        try {
            Integer userId = jwt.getUserIdFromToken(token);
            boolean result = orderService.deleteOrder(deleteDto.getId(), userId);
            return ResponseMessage.success(result ? "订单删除成功" : "订单删除失败");
        } catch (RuntimeException e) {
            return ResponseMessage.error(400, e.getMessage());
        } catch (Exception e) {
            return ResponseMessage.error(500, "服务器内部错误");
        }
    }

    // ========================== 获取订单列表 ==========================
    @GetMapping("/orderList")
    public ResponseMessage<?> getOrderList(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "8") Integer nums,
            @RequestParam(required = false) String sort,
            HttpServletRequest request) {
        String token = jwt.extractToken(request);
        if (token == null || !jwt.validateToken(token)) {
            return ResponseMessage.error(401, "请先登录");
        }

        try {
            // 验证是否是管理员
            if (!jwt.isAdmin(token)) {
                return ResponseMessage.error(403, "无权限访问");
            }

            // 获取订单列表
            Map<String, Object> result = orderService.getOrderList(page, nums, sort);
            return ResponseMessage.success(result);
        } catch (RuntimeException e) {
            return ResponseMessage.error(400, e.getMessage());
        } catch (Exception e) {
            return ResponseMessage.error(500, "服务器内部错误");
        }
    }

    // ========================== 获取我买到的订单 ==========================
    @GetMapping("/myOrders")
    public ResponseMessage<?> getMyOrders(HttpServletRequest request) {
        String token = jwt.extractToken(request);
        if (token == null || !jwt.validateToken(token)) {
            return ResponseMessage.error(401, "请先登录");
        }

        try {
            Integer userId = jwt.getUserIdFromToken(token);
            return ResponseMessage.success(orderService.getMyOrders(userId));
        } catch (RuntimeException e) {
            return ResponseMessage.error(400, e.getMessage());
        } catch (Exception e) {
            return ResponseMessage.error(500, "服务器内部错误");
        }
    }

    // ========================== 获取我卖出的订单 ==========================
    @GetMapping("/mySoldOrders")
    public ResponseMessage<?> getMySoldOrders(HttpServletRequest request) {
        String token = jwt.extractToken(request);
        if (token == null || !jwt.validateToken(token)) {
            return ResponseMessage.error(401, "请先登录");
        }

        try {
            Integer userId = jwt.getUserIdFromToken(token);
            return ResponseMessage.success(orderService.getMySoldOrders(userId));
        } catch (RuntimeException e) {
            return ResponseMessage.error(400, e.getMessage());
        } catch (Exception e) {
            return ResponseMessage.error(500, "服务器内部错误");
        }
    }
}